package cn.tom.tompicturebackend.controller;

import cn.tom.tompicturebackend.annotation.AuthCheck;
import cn.tom.tompicturebackend.common.BaseResponse;
import cn.tom.tompicturebackend.common.ResultUtils;
import cn.tom.tompicturebackend.constant.UserConstant;
import cn.tom.tompicturebackend.exception.BusinessException;
import cn.tom.tompicturebackend.exception.ErrorCode;
import cn.tom.tompicturebackend.manager.CosManager;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.utils.IOUtils;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@Slf4j
@RestController
public class FileController {
    @Resource
    private CosManager cosManager;
    /**
     * 测试文件上传
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @PostMapping("/test/upload")
    public BaseResponse<String> testUploadFile(@RequestPart("file") MultipartFile multipartFile) {
        //文件目录
        String fileName = multipartFile.getOriginalFilename();
        String filePath = String.format("/test/%s",fileName);
        File file = null;
        try{
            //上传文件
            file = File.createTempFile(filePath,null);
            multipartFile.transferTo(file);
            cosManager.putObject(filePath,file);

            return ResultUtils.success(filePath);

        }catch (Exception e){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"上传失败");
        }finally {
            if (file !=null)
            {
                //删除临时文件
                boolean delete = file.delete();
                if(!delete){
                    log.error("删除临时文件失败,filepath={}",filePath);
                }
            }
        }
    }

    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @GetMapping("/test/download/")
    public void testDownloadFile(String filePath, HttpServletResponse response) throws IOException{
        COSObjectInputStream cosObjectInputStream = null;
        try{
            COSObject cosObject = cosManager.getObject(filePath);
            cosObjectInputStream = cosObject.getObjectContent();

            //处理下载到的流
            byte[] bytes = IOUtils.toByteArray(cosObjectInputStream);

            //设置响应头
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition","attachment;filename="+filePath);

            //写入响应
            response.getOutputStream().write(bytes);
            response.getOutputStream().flush();
        }catch (Exception e){
            log.error("file download error.filepath = "+ filePath,e);
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"下载失败");

        }finally {
            if (cosObjectInputStream !=null){
                cosObjectInputStream.close();
            }
        }
    }
}
